﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Management;
using System.Net.NetworkInformation;
using System.Security.Principal;
using System.Text;
using System.Windows.Forms;

namespace iSet
{
    public partial class Setting : Form
    {
        #region Attributes

        QT.Windows.SafeTokenHandle pToken;

        System.Drawing.Point mousePoint;

        #endregion

        public Setting()
        {
            InitializeComponent();
        }

        private void Setting_Shown(object sender, EventArgs e)
        {
            DoSetting();
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            this.Close();
            this.Dispose();
        }

        private void DoSetting()
        {
            if (!QT.Windows.WinLogon.IsAdministrators())
            {
                DataTable dt = DB.GetUser();

                if (QT.Windows.WinLogon.Logon(dt.Rows[0]["username"].ToString(), QT.Security.AESHelper.AESDecrypt(dt.Rows[0]["pass"].ToString()), out pToken))
                {
                    using (pToken)
                    {
                        using (WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(pToken.DangerousGetHandle()))
                        {
                            SetIP();
                        }
                    }
                }
            }
            else
            {
                SetIP();
            }
        }

        private void SetIP()
        {
            try
            {
                //设置本机IP信息
                ManagementBaseObject inPar = null;
                ManagementBaseObject outPar = null;
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if (!(bool)mo["IPEnabled"]) continue;
                    if (mo["MACAddress"].ToString().Replace(":", "").ToUpper() == GlobalAttrib.Nid.ToUpper())
                    {
                        DataTable IPSetting = DB.GetIPSetting(GlobalAttrib.Sid);

                        #region IP

                        if (IPSetting.Rows[0]["isdhcp"].ToString().ToUpper() == "TRUE")
                        {
                            #region DHCP

                            try
                            {
                                //重置DNS为空  
                                mo.InvokeMethod("SetDNSServerSearchOrder", null);
                                //开启DHCP  
                                mo.InvokeMethod("EnableDHCP", null);

                                ShowIPResult("DHCP", true);
                                ShowMaskResult("DHCP", true);
                                ShowGateWayResult("DHCP", true);
                            }
                            catch
                            {
                                ShowIPResult("DHCP", false);
                                ShowMaskResult("DHCP", false);
                                ShowGateWayResult("DHCP", false);
                                return;
                            }

                            #endregion
                        }
                        else
                        {
                            #region Static

                            try
                            {
                                //设置IP地址和子网掩码
                                inPar = mo.GetMethodParameters("EnableStatic");
                                inPar["IPAddress"] = new string[] { IPSetting.Rows[0]["ip"].ToString() };
                                inPar["SubnetMask"] = new string[] { IPSetting.Rows[0]["mask"].ToString() };
                                outPar = mo.InvokeMethod("EnableStatic", inPar, null);

                                ShowIPResult(IPSetting.Rows[0]["ip"].ToString(), true);
                                ShowMaskResult(IPSetting.Rows[0]["mask"].ToString(), true);
                            }
                            catch (Exception ex)
                            {
                                ShowIPResult(IPSetting.Rows[0]["ip"].ToString(), false);
                                ShowMaskResult(IPSetting.Rows[0]["mask"].ToString(), false);
                                MessageBox.Show(ex.Message);
                            }

                            try
                            {
                                //设置网关地址
                                inPar = mo.GetMethodParameters("SetGateways");
                                inPar["DefaultIPGateway"] = new string[] { IPSetting.Rows[0]["gateway"].ToString() };
                                outPar = mo.InvokeMethod("SetGateways", inPar, null);

                                ShowGateWayResult(IPSetting.Rows[0]["gateway"].ToString(), true);
                            }
                            catch
                            {
                                ShowGateWayResult(IPSetting.Rows[0]["gateway"].ToString(), false);
                            }

                            #endregion

                        }

                        #endregion

                        #region DNS

                        if (IPSetting.Rows[0]["autodns"].ToString().ToUpper() == "FALSE")
                        {
                            try
                            {
                                //设置DNS
                                inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
                                inPar["DNSServerSearchOrder"] = new string[] { IPSetting.Rows[0]["dns1"].ToString(), IPSetting.Rows[0]["dns2"].ToString() };
                                outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null);

                                ShowDnsResult(IPSetting.Rows[0]["dns1"].ToString() + " " + IPSetting.Rows[0]["dns2"].ToString(), true);
                            }
                            catch
                            {
                                ShowDnsResult(IPSetting.Rows[0]["dns1"].ToString() + " " + IPSetting.Rows[0]["dns2"].ToString(), false);
                            }
                        }
                        else
                        {
                            ShowDnsResult("DHCP", true);
                        }

                        #endregion
                    }

                }
            }
            catch
            {
                MessageBox.Show("系统错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (DB.GetSettingID(GlobalAttrib.Nid) != "0") DB.UpdateSetting(GlobalAttrib.Nid, GlobalAttrib.Sid);
            else DB.AddSetting(GlobalAttrib.Nid, GlobalAttrib.Sid);
        }

        private void ShowIPResult(string ip, bool b)
        {
            this.lblIP.Text = ip;

            PictureBox picbox = new PictureBox();
            if (b)
            {
                picbox.Image = Properties.Resources.right;
                picbox.Height = Properties.Resources.right.Height;
                picbox.Width = Properties.Resources.right.Width;
            }
            else
            {
                picbox.Image = Properties.Resources.error;
                picbox.Height = Properties.Resources.error.Height;
                picbox.Width = Properties.Resources.error.Width;
            }
            picbox.Location = new Point(this.lblIP.Location.X + this.lblIP.Width + 5, this.lblIP.Location.Y + this.lblIP.Height / 2 - picbox.Height / 2);
            picbox.BorderStyle = BorderStyle.None;
            this.panel1.Controls.Add(picbox);
        }

        private void ShowMaskResult(string mask, bool b)
        {
            this.lblMask.Text = mask;

            PictureBox picbox = new PictureBox();
            if (b)
            {
                picbox.Image = Properties.Resources.right;
                picbox.Height = Properties.Resources.right.Height;
                picbox.Width = Properties.Resources.right.Width;
            }
            else
            {
                picbox.Image = Properties.Resources.error;
                picbox.Height = Properties.Resources.error.Height;
                picbox.Width = Properties.Resources.error.Width;
            }
            picbox.Location = new Point(this.lblMask.Location.X + this.lblMask.Width + 5, this.lblMask.Location.Y + this.lblMask.Height / 2 - picbox.Height / 2);
            picbox.BorderStyle = BorderStyle.None;
            this.panel1.Controls.Add(picbox);
        }

        private void ShowGateWayResult(string gateway, bool b)
        {
            this.lblGateWay.Text = gateway;

            PictureBox picbox = new PictureBox();
            if (b)
            {
                picbox.Image = Properties.Resources.right;
                picbox.Height = Properties.Resources.right.Height;
                picbox.Width = Properties.Resources.right.Width;
            }
            else
            {
                picbox.Image = Properties.Resources.error;
                picbox.Height = Properties.Resources.error.Height;
                picbox.Width = Properties.Resources.error.Width;
            }
            picbox.Location = new Point(this.lblGateWay.Location.X + this.lblGateWay.Width + 5, this.lblGateWay.Location.Y + this.lblGateWay.Height / 2 - picbox.Height / 2);
            picbox.BorderStyle = BorderStyle.None;
            this.panel1.Controls.Add(picbox);
        }

        private void ShowDnsResult(string dns, bool b)
        {
            this.lblDNS.Text = dns;

            PictureBox picbox = new PictureBox();
            if (b)
            {
                picbox.Image = Properties.Resources.right;
                picbox.Height = Properties.Resources.right.Height;
                picbox.Width = Properties.Resources.right.Width;
            }
            else
            {
                picbox.Image = Properties.Resources.error;
                picbox.Height = Properties.Resources.error.Height;
                picbox.Width = Properties.Resources.error.Width;
            }
            picbox.Location = new Point(this.lblDNS.Location.X + this.lblDNS.Width + 5, this.lblDNS.Location.Y + this.lblDNS.Height / 2 - picbox.Height / 2);
            picbox.BorderStyle = BorderStyle.None;
            this.panel1.Controls.Add(picbox);
        }

        private void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.mousePoint.X = e.X;
                this.mousePoint.Y = e.Y;
            }
        }

        private void panel1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Top = Control.MousePosition.Y - this.mousePoint.Y;
                this.Left = Control.MousePosition.X - this.mousePoint.X;
            }
        }
    }
}
